package com.example.testi18n.http;

import com.example.testi18n.exception.IResponseEnum;
import lombok.Data;

/**
 * @author xiaobendan
 * @version v1.0.0
 * @className JsonResult
 * @package com.example.testi18n.http
 * @description 响应结构
 * @date 2022-09-26 14:48
 */
@Data
public class JsonResult<T> {
    /**
     * 状态码
     */
    private Integer code;
    /**
     * 消息
     */
    private String message;

    /**
     * 服务器时间戳
     */
    private Long timestamp = System.currentTimeMillis();

    /**
     * 参数信息
     */
    private T data;

    /**
     * 返回成功，传入返回体具体出參
     */
    public static <T> JsonResult<T> ok(T data) {
        JsonResult<T> result = new JsonResult<T>();
        result.code = 0;
        result.message = "success";
        result.data = data;
        return result;
    }

    /**
     * 提供给部分不需要出參的接口
     */
    public static <T> JsonResult<T> ok() {
        return ok(null);
    }

    /**
     * 自定义错误信息
     */
    public static <T> JsonResult<T> error(Integer code, String message) {
        JsonResult<T> result = new JsonResult<T>();
        result.code = code;
        result.message = message;
        return result;
    }

    /**
     * 请求失败，返回错误码及错误信息
     */
    public static <T> JsonResult<T> error(Integer code, String message, T data) {
        JsonResult<T> result = new JsonResult<T>();
        result.code = code;
        result.message = message;
        result.data = data;
        return result;
    }

    public static<T> JsonResult<T> error(IResponseEnum responseEnum) {
        JsonResult<T> result = new JsonResult<>();
        result.code = responseEnum.getCode();
        result.message = responseEnum.getI18nMessage();
        return result;
    }

    public boolean isOk() {
        return this.code == 0;
    }
}
